package com.bhs.sansonglogistics.ui.waybill;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.ArriveBean;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.PictureBean;
import com.bhs.sansonglogistics.bean.PictureShowBean;
import com.bhs.sansonglogistics.bean.ShipmentsBean;
import com.bhs.sansonglogistics.bean.WaybillDetailsBean;
import com.bhs.sansonglogistics.dialog.BottomSelectArriveAddressDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.PictureSelectAdapter;
import com.bhs.sansonglogistics.ui.adapter.PictureShowAdapter;
import com.bhs.sansonglogistics.ui.adapter.WaybillOrderAdapter;
import com.bhs.sansonglogistics.ui.order.OrderDetailsActivity;
import com.bhs.sansonglogistics.ui.order.SelectOrderActivity;
import com.bhs.sansonglogistics.ui.order.ShipmentsActivity;
import com.bhs.sansonglogistics.ui.waybill.WaybillReuse;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;
import wang.relish.widget.vehicleedittext.VehicleKeyboardHelper;

/**
 * 调整运单
 */
public class AdjustWaybillActivity extends BaseActivity implements NetCallBack, View.OnClickListener {

    private RecyclerView mRvList;//订单
    private WaybillOrderAdapter waybillAdapter;


    private RecyclerView mRvPicture;//照片
    private PictureSelectAdapter pictureShowAdapter;
    private final List<PictureBean> pictureBeanList = new ArrayList<>();


    private final WaybillReuse waybillReuse = new WaybillReuse();
    private EditText mEtLicensePlateNumber;
    private EditText mEtDriver;
    private EditText mEtDriverPhone;
    private Button mBtnAddOrder;
    private Button mBtnSubmit;
    private String reach;
    private String orders = "";
    private int line_id;
    private StringBuilder deliver_sn = new StringBuilder();//变更后订单号
    private StringBuilder del_deliver_sn = new StringBuilder();//删除的订单号
    private StringBuilder add_deliver_sn = new StringBuilder();//新增的订单号
    private ArrayList<OrderGoodsBean> deleteOrder = new ArrayList<>();

    private ArrayList<OrderGoodsBean> protogenesis = new ArrayList<>();
    private String outlets_id;
    private TextView mTvBranch;
    private final int SPECIAL_RAILWAY_LINE = 101;
    private int maxSelectNum = 3;
    private String old_outlets_id;

    @Override
    public int initLayout() {
        return R.layout.activity_adjust_waybill;
    }

    @Override
    public void initView() {
        waybillReuse.initView(this);
        mEtLicensePlateNumber = findViewById(R.id.et_license_plate_number);
        mRvList = findViewById(R.id.rv_list);
        mRvPicture = findViewById(R.id.rv_picture);
        mEtDriver = findViewById(R.id.et_driver);
        mEtDriverPhone = findViewById(R.id.et_driver_phone);
        mBtnAddOrder = findViewById(R.id.btn_add_order);
        mBtnAddOrder.setOnClickListener(this);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mTvBranch = findViewById(R.id.tv_branch);
        mTvBranch.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);
        VehicleKeyboardHelper.bind(mEtLicensePlateNumber); // 为输入框绑定车牌号输入键盘
        loadingPopupShow();
        networkRequest(netApi.getWaybillDetail(getIntent().getStringExtra("waybill_sn")), this);
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    orders = result.getData().getStringExtra("orders");
                    ArrayList<OrderGoodsBean> callBack = result.getData().getParcelableArrayListExtra("ordersInfo");
                    //新增单
                    for (OrderGoodsBean orderGoodsBean : callBack) {
                        boolean isHas = false;
                        for (OrderGoodsBean datum : waybillAdapter.getData()) {
                            if (orderGoodsBean.getDeliver_sn().equals(datum.getDeliver_sn())) {
                                isHas = true;
                                break;
                            }
                        }
                        if (!isHas) {
                            waybillAdapter.addData(orderGoodsBean);
                        }
                    }

                    waybillAdapter.notifyDataSetChanged();
                }

            }
        });

    }

    @Override
    public void initData() {
        waybillAdapter = new WaybillOrderAdapter(2);
        mRvList.setAdapter(waybillAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(this));
        pictureShowAdapter = new PictureSelectAdapter(maxSelectNum, this);
        mRvPicture.setAdapter(pictureShowAdapter);
        mRvPicture.setLayoutManager(new GridLayoutManager(mContext, 3));
        waybillAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                boolean isHas = false;
                OrderGoodsBean item = waybillAdapter.getData().get(position);
                //有些清空没有逗号 做两次判断
                if (!TextUtils.isEmpty(orders)) {
                    orders = orders.replace(item.getDeliver_sn() + ",", "");
                    orders = orders.replace(item.getDeliver_sn(), "");
                }
                if (!MyUtils.isEmpty(deleteOrder)) {
                    for (OrderGoodsBean orderGoodsBean : deleteOrder) {
                        if (orderGoodsBean.getDeliver_sn().equals(item.getDeliver_sn())) {
                            isHas = true;
                        }
                    }
                }
                if (!isHas) {
                    deleteOrder.add(item);
                }
                waybillAdapter.remove(position);
            }
        });

        waybillAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String deliver_sn = waybillAdapter.getData().get(position).getDeliver_sn();
                startActivity(new Intent(mActivity, OrderDetailsActivity.class).putExtra("deliver_sn", deliver_sn));
            }
        });
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            WaybillDetailsBean waybillDetailsBean = new Gson().fromJson(json, WaybillDetailsBean.class);
            if (waybillDetailsBean.isStatus()) {
                waybillReuse.initData(waybillDetailsBean.getData());
                setData(waybillDetailsBean.getData());
            } else {
                ToastUtil.show(waybillDetailsBean.getMsg());
            }
        } else if (requestCode == 110) {
            loadingPopupDismiss();
            add_deliver_sn.delete(0, add_deliver_sn.length());
            del_deliver_sn.delete(0, del_deliver_sn.length());
            deliver_sn.delete(0, deliver_sn.length());
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                finish();
            }
        } else if (requestCode == SPECIAL_RAILWAY_LINE) {
            loadingPopupDismiss();
            ShipmentsBean shipmentsBean = new Gson().fromJson(json, ShipmentsBean.class);
            if (shipmentsBean.isStatus()) {
                arriveBeans.clear();
                ShipmentsBean.DataDTO.InfoDTO data = shipmentsBean.getData().getInfo();
                arriveBeans.addAll(data.getOutlets_list());
            }
        }
    }

    private void setData(WaybillDetailsBean.DataDTO waybillData) {
        WaybillDetailsBean.DataDTO.WaybillInfoDTO data = waybillData.getWaybill_info();
        outlets_id = waybillData.getWaybill_info().getOutlets_id();
        old_outlets_id = waybillData.getWaybill_info().getOutlets_id();
        mEtLicensePlateNumber.setText(data.getLicense_plate());
        mEtDriver.setText(data.getDriver_name());
        mEtDriverPhone.setText(data.getDriver_mobile());
        protogenesis.addAll(waybillData.getDeliver_order_list());
        waybillAdapter.setNewData(waybillData.getDeliver_order_list());
        for (OrderGoodsBean orderGoodsBean : waybillData.getDeliver_order_list()) {
            orderGoodsBean.setCurrent(true);
            orders = orders + orderGoodsBean.getDeliver_sn() + ",";
        }
        reach = waybillData.getLine_info().getStart_city() + "—" + waybillData.getLine_info().getEnd_city();
        reach = reach.replace("市", "");
        line_id = waybillData.getLine_info().getLine_id();
        if (!TextUtils.isEmpty(data.getImages())) {
            String[] images = data.getImages().split("\\|\\|");
            for (String image : images) {
                pictureBeanList.add(new PictureBean(image, image));
                pictureShowAdapter.localMedia.add(LocalMedia.generateHttpAsLocalMedia(MyUtils.watermark(image)));
            }
        }

        if (pictureShowAdapter.getMaxSelectNum() > pictureBeanList.size()) {
            pictureBeanList.add(new PictureBean(2));
        }
        pictureShowAdapter.setNewData(pictureBeanList);
        String info = String.format("到站公司：%s\n线路经理：%s\n到站电话：%s\n到站地址：%s",
                data.getOutlets_name(), data.getOutlets_county(), data.getOutlets_mobile(), data.getOutlets_address());
        mTvBranch.setText(info);
        networkRequest(netApi.getSpecialLineInfo(line_id), this, SPECIAL_RAILWAY_LINE);
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private final List<ArriveBean> arriveBeans = new ArrayList<>();

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_add_order) {
            intentActivityResultLauncher.launch(new Intent(mActivity, SelectOrderActivity.class)
                    .putExtra("orders", orders).putExtra("line_id", line_id)
                    .putParcelableArrayListExtra("deleteOrder", deleteOrder)
                    .putExtra("reach", reach));
        } else if (view.getId() == R.id.btn_submit) {
            submit();
        } else if (view.getId() == R.id.tv_branch) {
            BottomSelectArriveAddressDialog addressDialog = new BottomSelectArriveAddressDialog(mContext, arriveBeans);
            new XPopup.Builder(mContext)
                    .asCustom(addressDialog)
                    .show();
            addressDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    outlets_id = id;
                    mTvBranch.setText(info);
                }
            });
        }
    }

    private void submit() {

        if (!MyUtils.isCarnumberNO(mEtLicensePlateNumber.getText().toString())) {
            ToastUtil.show("请输入正确的车牌号");
            return;
        }
        if (!MyUtils.isPhone(mEtDriverPhone.getText().toString())) {
            ToastUtil.show("请输入正确的手机号");
            return;
        }

        if (waybillAdapter.getData().size() == 0) {
            ToastUtil.show("必须有一个订单");
            return;
        }
        for (OrderGoodsBean datum : waybillAdapter.getData()) {
            deliver_sn.append(datum.getDeliver_sn());
            deliver_sn.append(",");
        }
        deliver_sn.delete(deliver_sn.length() - 1, deliver_sn.length());


        for (OrderGoodsBean protogenesi : protogenesis) {
            boolean isHas = false;
            for (OrderGoodsBean datum : waybillAdapter.getData()) {
                if (protogenesi.getDeliver_sn().equals(datum.getDeliver_sn())) {
                    isHas = true;
                    break;
                }
            }
            //删除的单
            if (!isHas) {
                del_deliver_sn.append(protogenesi.getDeliver_sn());
                del_deliver_sn.append(",");
            }

        }

        for (OrderGoodsBean protogenesi : waybillAdapter.getData()) {
            boolean isHas = false;
            for (OrderGoodsBean datum : protogenesis) {
                if (protogenesi.getDeliver_sn().equals(datum.getDeliver_sn())) {
                    isHas = true;
                    break;
                }
            }
            //新曾地单
            if (!isHas) {
                add_deliver_sn.append(protogenesi.getDeliver_sn());
                add_deliver_sn.append(",");
            }

        }

        if (!TextUtils.isEmpty(del_deliver_sn)) {
            del_deliver_sn.delete(del_deliver_sn.length() - 1, del_deliver_sn.length());
        }

        if (!TextUtils.isEmpty(add_deliver_sn)) {
            add_deliver_sn.delete(add_deliver_sn.length() - 1, add_deliver_sn.length());
        }

        Map<String, String> map = new ArrayMap<>();
        map.put("waybill_sn", getIntent().getStringExtra("waybill_sn"));
        map.put("deliver_sn", deliver_sn.toString());
        map.put("del_deliver_sn", del_deliver_sn.toString());
        map.put("add_deliver_sn", add_deliver_sn.toString());
        map.put("license_plate", mEtLicensePlateNumber.getText().toString());
        map.put("driver_name", mEtDriver.getText().toString());
        map.put("driver_mobile", mEtDriverPhone.getText().toString());
        map.put("images", pictureShowAdapter.getImages());
        map.put("line_id", String.valueOf(line_id));
        map.put("outlets_id", outlets_id);
        map.put("old_outlets_id", old_outlets_id);

        networkRequest(netApi.adjustWaybill(map), this, 110);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mEtDriver.setFocusable(true);
        mEtDriver.setFocusableInTouchMode(true);
    }

}